package com.fzrskj.cloud.free.user.utils.agent;

import com.fzrskj.cloud.free.sys.bean.SysAgentRelationBean;
import com.fzrskj.cloud.free.sys.dao.SysAgentRelationDao;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.dao.UserAccountDao;
import org.apache.commons.collections.map.HashedMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * InitDataSyncAgentRealtionHelper.
 *
 * @author zj.
 *         Created on 2019/9/9 0009.
 */
public class InitDataSyncAgentRelationHelper {
    /**
     * 同步代理关系.
     * @param currentAgentId 当前操作的代理ID.
     * @param taskAgentId  目标代理ID.
     * @param isAdd 是否是添加.
     */
    public static void syncAgentRelation(Integer currentAgentId, Integer taskAgentId, Boolean isAdd) {
        Map<String, Object> cdt = new HashedMap();
        cdt.put("agentId", taskAgentId);
        SysAgentRelationDao relationDao = new SysAgentRelationDao();
        SysAgentRelationBean relationBean = relationDao.queryOneSysAgentRelation(cdt);
        List<String> idList = new ArrayList<>();
        if (null != relationBean) {
            String[] idString = relationBean.getSubIdList().split(",");
            for (String id : idString) {
                idList.add(id);
            }
        }

        String thisId = String.valueOf(currentAgentId);

        if (isAdd) {
            if (!idList.contains(thisId)) {
                idList.add(thisId);
            }
        } else {
            if (idList.contains(thisId)) {
                idList.remove(thisId);
            }
        }

        String idNews = String.join(",", idList);
        Map<String, Object> values = new HashedMap();
        values.put("subIdList", idNews);
        if (null == relationBean) {
            values.put("agentId", taskAgentId);
            relationDao.newSysAgentRelation(values);
        } else {
            relationDao.modSysAgentRelation(values, cdt);
        }

        UserAccountDao accountDao = new UserAccountDao();
        UserAccount targetAgent = accountDao.getUserAccountWithoutAgent(taskAgentId);
        if (null != targetAgent) {
            syncAgentRelation(currentAgentId, targetAgent.getAgentId(), isAdd);
        }
    }
}
